package cn.lavender.web.response.interceptor;

import cn.lavender.web.response.annotation.RestResponse;
import cn.lavender.web.response.entity.CommonConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * <p>
 *
 * @ApiResponse 注解拦截器
 * </p>
 * @author: zhu.chen
 * @date: 2021/3/29
 * @version: v1.0.0
 */
@Slf4j
@Component
public class ApiResponseInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Class<?> clazz = handlerMethod.getBeanType();
            Method method = handlerMethod.getMethod();
            if (clazz.isAnnotationPresent(RestResponse.class)) {
                request.setAttribute(CommonConstant.API_TAG, clazz.getAnnotation(RestResponse.class));
            } else if (method.isAnnotationPresent(RestResponse.class)) {
                request.setAttribute(CommonConstant.API_TAG, method.getAnnotation(RestResponse.class));
            }
        }
        return true;
    }

}
